package org.xhy.circuitbreaker.proxy;

import net.sf.cglib.proxy.Enhancer;
import org.springframework.beans.BeanUtils;
import org.xhy.circuitbreaker.ICircuitBreakerController;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Set;

/**
 * @description:
 * @gitee: https://gitee.com/XhyQAQ
 * @copyright: B站: https://space.bilibili.com/152686439
 * @Author: Xhy
 * @CreateTime: 2024-06-04 16:37
 */
public class CglibFactory{

    public static <T> T getProxy(Object bean, Set<Integer> methods, ICircuitBreakerController circuitBreakerController) throws NoSuchFieldException, IllegalAccessException {
        final Class<?> aClass = bean.getClass();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(aClass);
        enhancer.setCallback(new CircuitBreakerProxy(bean,methods,circuitBreakerController));
        final T t = (T) enhancer.create();
        // 将原始对象的字段值复制到代理对象上
        copyBeanProperties(bean, t);
        return t;
    }
    private static void copyBeanProperties(Object source, Object target) {
        try {
            // 获取源对象的所有字段,包括非 public 字段
            Field[] fields = source.getClass().getDeclaredFields();
            for (Field field : fields) {
                // 设置可访问性,以便我们可以访问 private 字段
                field.setAccessible(true);
                // 将字段值从源对象复制到目标对象
                field.set(target, field.get(source));
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Failed to copy bean properties", e);
        }
    }
}
